package com.example.mychat.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.mychat.entity.Likes;
import com.example.mychat.entity.Message;
import com.example.mychat.entity.Thumb;
import com.example.mychat.mapper.LikesMapper;
import com.example.mychat.mapper.MessageMapper;
import com.example.mychat.mapper.ThumbMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Tag(name = "点赞控制")
@Controller
@RequestMapping("/thumb")
public class ThumbController {
    @Resource
    ThumbMapper thumbMapper;

    @Resource
    MessageMapper messageMapper;

    @Resource
    LikesMapper likesMapper;

    @Resource
    HttpServletRequest req;

    @Operation(description = "点赞")
    @PostMapping("")
    @ResponseBody
    public String thumb(@RequestParam Long messageId) {
        String username = String.valueOf(req.getSession().getAttribute("username"));
        if (username.equals("null")) {
            return "用户未登录";
        }
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("messageId", messageId);
        Thumb thumb = thumbMapper.selectOne(queryWrapper);
        thumb.setNum(thumb.getNum() + 1);
        thumbMapper.update(thumb, queryWrapper);
        queryWrapper.clear();
        queryWrapper.eq("id", messageId);
        Message message = messageMapper.selectOne(queryWrapper);
        String beLikedName = message.getUsername();
        queryWrapper.clear();
        queryWrapper.eq("username", username);
        queryWrapper.eq("beLikedName", beLikedName);
        Likes likes = likesMapper.selectOne(queryWrapper);
        if (likes == null) {
            likesMapper.insert(new Likes(username, beLikedName, 1));
        } else {
            likes.setThumbNum(likes.getThumbNum() + 1);
            likesMapper.update(likes, queryWrapper);
        }
        return "success";
    }
}
